<style lang="less">
@import "../../styles/common.less";
.blue-tag{
    margin:2px 4px;
    display: inline-block;
    padding:2px 6px;
    color:#fff;
    background:#2d8cf0;
}
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <Button type="primary" @click="handleAddClassroom" style="margin-right: 3px">添加教室</Button>
      </Row>
      <Row>
        <Input
          v-model.trim="queryForm.group_name"
          @on-enter="searchClassroom"
          placeholder="请输入集团名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.campus_name"
          @on-enter="searchClassroom"
          placeholder="请输入校区名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.name"
          @on-enter="searchClassroom"
          placeholder="请输入教室名称"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Input
          v-model.trim="queryForm.num"
          @on-enter="searchClassroom"
          placeholder="请输入教室编号"
          style="width: 150px;margin-right:3px"
        ></Input>
        <Button @click="searchClassroom" type="primary">查询</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table :columns="classroomColumn" :data="classroomData" :loading="tableLoading"></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="totalClassroom"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="getClassroom"
        show-total
      >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalClassroom}}条</Page>
    </Row>

    <Modal
      v-model="addClassroomModal"
      v-bind:title="modalTitle"
      :scrollable="true"
      class-name="vertical-center-modal"
      :mask-closable="false"
      @on-cancel="resetForm('classroomInfoForm')"
    >
      <Form
        ref="classroomInfoForm"
        :label-width="80"
        :model="classroomInfo"
        :rules="classroomInfoRules"
      >
        <FormItem label="集团名称" prop="group_id">
          <Select v-model="classroomInfo.group_id" style="width:200px" @on-change="getCampusData">
              <Option v-for="item in allGroupData" :value="item._id" :key="item._id">{{ item.group_name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="校区名称" prop="campus_id">
          <Select :disabled="campusData.length<=0" v-model="classroomInfo.campus_id" style="width:200px">
              <Option v-for="item in campusData" :value="item._id" :key="item._id">{{ item.campus_name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="教室名称" prop="name">
            <Input v-model.trim="classroomInfo.name" placeholder="请填写教室名称" />
        </FormItem>
        <FormItem label="教室编号" prop="num">
            <Input
            placeholder="请填写教室编号"
            style="width: 100%"
            v-model.trim="classroomInfo.num"
            />
        </FormItem>
        <FormItem label="绑定设备" prop="device_ids">
            <!-- <Input placeholder="请填写绑定设备" v-model.trim="classroomInfo.related_devices" /> -->
            <CheckboxGroup v-model="classroomInfo.device_ids">
                <Checkbox :label="item.ipc_id" v-for="item in ipcList" :key="item.ipc_id">
                    <span>{{item.ipc_name}}({{item.ipc_id}})</span>
                </Checkbox>
            </CheckboxGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitClassroom('classroomInfoForm')">提交</Button>
      </div>
    </Modal>

    <!-- <Modal v-model="uploadModal" @on-cancel="hideUploadModal">
      <div slot="header">
        <p>
          导入表格
          <span style="font-weight: 100;font-size: 12px;margin-left: 5px">
            (请严格按照
            <a :href="excelFile" download="模板.xlsx">模板</a>格式上传表格)
          </span>
        </p>
      </div>
      <HorizonUploader ref="uploader"></HorizonUploader>
      <div slot="footer">
        <Button type="primary" @click="handleUpload">上传</Button>
      </div>
    </Modal> -->
  </div>
</template>

<script>
import {
  getClassroom,
  addClassroom,
  updateClassroom,
  deleteClassroom,
} from "../../controllers/classroom";

import {
  getClassgroup,
  getClasscampus,
} from "../../controllers/classgroup";


import ipcSetting from '../../controllers/ipcSetting';
import HorizonUploader from "./components/HorizonUploader.vue";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";
import _ from "lodash";
import iconDelete from "../../images/delete.png";
import iconEdit from "../../images/edit.png";

import excelFile from "../../assets/staffExcel.xlsx";

export default {
  name:'classroom',
  components: {
    HorizonUploader,
    Tooltip,
    Btn
  },
  data() {
    return {
      addClassroomModal: false,
      tableLoading: true,
      queryForm:{
          group_name:'',
          campus_name:'',
          name:'',
          num:''
      },
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalClassroom: 0,
      classroomColumn: [
        {
          title: "集团名称",
          align: "center",
          key: "group_name",
          width: 200
        },
        {
          title: "校区名称",
          key: "campus_name",
          align: "center",
          width: 200
        },
        {
          title: "教室名称",
          align: "center",
          key: "name",
          width: 200
        },
        {
          title: "教室编号",
          key: "num",
          align: "center",
          width: 200
        },
        {
          title: "绑定设备",
          align: "center",
          minWidth: 400,
          render: (h, {row, column, index}) => {
              const devices = row.related_devices;
              return (
                  <div>
                    {
                        devices.map(item=>{
                            return (
                                <span class="blue-tag">{item.device_name}({item.device_id})</span>
                            )
                        })
                    }
                  </div>
              )
          }
        },
        {
          title: "操作",
          align: "center",
          width: 240,
          render: (h, { row, column, index }) => {
            const _id = row._id;
            return (
              <div class="operation">
                <Tooltip content="编辑" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconEdit})` }}
                    onClick={() => this.handleEditClassroom(row)}
                  />
                </Tooltip>
                <Tooltip content="删除" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconDelete})` }}
                    onClick={() => this.handleDelClassroom(_id, row.name)}
                  />
                </Tooltip>
              </div>
            );
          }
        }
      ],
      classroomData: [],
      ipcList:[],
      classroomInfo: {
        _id:'',
        group_id:'',
        campus_id:'',
        name:'',
        num:'',
        device_ids:[]
      },
      modalTitle: "添加正式员工",
      classroomInfoRules: {
          group_id: [
            { required: true, message: "请选择集团", trigger: "blur" }
          ],
          campus_id: [
            { required: true, message: "请选择校区", trigger: "blur" }
          ],
          name: [
            { required: true, message: "请输入教室名称", trigger: "blur" }
          ],
          num: [
              {required: true, message: "请输入教室编号", trigger: "blur"}
          ],
        //   device_ids: [
        //       {required: true, message: "请选择关联设备", trigger: "blur"}
        //   ],
      },
      uploadModal: false,
      excelFile: excelFile,

      allGroupData:[],
      campusData:[]
    };
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    },
  },
  //待考虑：初次加载表格的时机
  created() {
    this.loadclassgroupData()
    this.loadclassroomData();
    this.getIpcList();
  },
  methods: {
    loadclassgroupData() {
      getClassgroup({
          page_num:1, 
          page_size:1000, 
        })
        .then(res => {
          this.allGroupData = res.data.result||[]
        })
    },
    getCampusData(group_id,isEdit){
      this.campusData = []
      !isEdit && (this.classroomInfo.campus_id = '')
      if(group_id){
        getClasscampus({
          group_id
        }).then(res=>{
          const { code, data} = res
          if(code===0){
            this.campusData = data||[]
          }
        })
      }
    },
    getClassroom(page) {
      this.currentPage = page;
      this.tableLoading = true;
      this.loadclassroomData();
    },
    getIpcList(){
        ipcSetting.loadIpcList().then(res=>{
            this.ipcList = (res.data||[]).filter(item=>item.ipc_type==='Julong_jHD23'&&item.ipc_capture_status===0)
        })
    },
    handleAddClassroom(type) {
      this.modalTitle = "添加教室";
      this.classroomInfo._id = null;
      this.addClassroomModal = true;
      if(this.allGroupData.length){
        this.classroomInfo.group_id = this.allGroupData[0]._id
        this.getCampusData(this.allGroupData[0]._id)
      }
      if(this.ipcList.length===0){
          this.getIpcList()
      }
    },
    findValByKey(ary,key,val,requiredKey){
      for(let item of ary){
        if(item[key]===val){
          return item[requiredKey]
        }
      }
      return ''
    },
    handleSubmitClassroom(form) {
      const submitInfo = Object.assign({},this.classroomInfo)
      this.$refs[form].validate(valid => {
        if (valid) {
          submitInfo.group_name = this.findValByKey(this.allGroupData,'_id',submitInfo.group_id,'group_name')
          submitInfo.campus_name = this.findValByKey(this.campusData,'_id',submitInfo.campus_id,'campus_name')
          if(submitInfo._id){
            updateClassroom(
                submitInfo
            ).then(res => {
                if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassroomModal = false;
                this.resetForm(form);
                this.getClassroom(this.currentPage);
                }
            });
          }else{
            addClassroom(
              submitInfo
            ).then(res => {
              if (res.code == 0) {
                this.$Message.success("提交成功!");
                this.addClassroomModal = false;
                this.resetForm(form);
                this.getClassroom(this.currentPage);
              }
            });
          }
        } else {
          this.$Message.error("填写项目验证失败!");
        }
      });
    },
    handleDelClassroom(id, name) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除教室【" + name + "】？",
        onOk: () => {
          // 删除基本信息
          deleteClassroom({ _id: [id] }).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.getClassroom(this.currentPage);
            }
          });
        }
      });
    },
    handleEditClassroom(row) {
      const data = row || {};
      this.modalTitle = "编辑教室";
      this.classroomInfo._id = data._id;
      this.classroomInfo.group_id = data.group_id;
      if(data.group_id){
        this.getCampusData(data.group_id,true)
      }
      this.classroomInfo.campus_id = data.campus_id;
      this.classroomInfo.name = data.name;
      this.classroomInfo.num = data.num;
      this.classroomInfo.device_ids = data.related_devices.map(item=>item.device_id);
      this.addClassroomModal = true;
      if(this.ipcList.length===0){
          this.getIpcList()
      }
    },
    searchClassroom() {
      //to-do:检验关键词
      this.currentPage = 1;
      this.tableLoading = true;
      this.loadclassroomData();
    },
    loadclassroomData() {
      getClassroom({
          page_num:this.currentPage, 
          page_size:this.pageSize, 
          ...this.queryForm
        })
        .then(json => {
          let { total, data } = transclassroomData(json);
          this.totalClassroom = total;
          this.classroomData = data;
          this.tableLoading = false;
          let tmp = _.map(data, item => item.uid);
          return tmp;
        })
        // .then(uids => this.asyncAvatar(uids));
    },
    resetForm(form) {
      //解决对话框消失的时候字体变化问题
      setTimeout(() => {
        this.$refs[form].resetFields();
        this.classroomInfo._id = null;
      }, 500);
    },
    handleUpload() {
      if (!this.$refs["uploader"].hasFile) {
        this.$Message.error("请先选择文件");
        return;
      }
      var formData = new FormData();
      formData.append("file", this.$refs["uploader"].file);
      uploadclassroomData(formData).then(json => {
        if (json.code == 0) {
          this.$Message.success(json.msg);
          this.hideUploadModal();
          this.getClassroom(this.currentPage);
        }
      });
    },
    hideUploadModal() {
      this.$refs["uploader"].reset();
      this.uploadModal = false;
    },
  }
};

function transclassroomData(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { total: 0, result: {} };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined) {
    return { total: 0, result: {} };
  }

  let { total, result } = data;

  return {
    total,
    data: result
  };
}

</script>